#!/usr/bin/env python3

# Copyright 2021 Tier IV, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import hashlib
import pathlib
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSDurabilityPolicy
from rclpy.qos import QoSProfile
from autoware_external_api_msgs.msg import MapHash


class MapHashGenerator(Node):

    def __init__(self):
        super().__init__('map_hash_generator')
        qos_profile = QoSProfile(depth=1, durability=QoSDurabilityPolicy.TRANSIENT_LOCAL)
        msg = MapHash()
        msg.lanelet = self.generateFileHash(self.declare_parameter('lanelet2_map_path').value)
        self.pub = self.create_publisher(MapHash, '/api/autoware/get/map/info/hash', qos_profile)
        self.pub.publish(msg)

    @staticmethod
    def generateFileHash(path):
        path = pathlib.Path(path)
        if path.exists():
            with path.open('rb') as fp:
                return hashlib.sha256(fp.read()).hexdigest()
        return ''


def main(args=None):
    rclpy.init(args=args)
    node = MapHashGenerator()
    rclpy.spin(node)
    rclpy.shutdown()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
